#include <iostream>
#include <jsoncpp/json/json.h>
#include <memory>
#include <sstream>

bool serialize(const Json::Value &json_value, std::string &json_string) {
    /* 1.定义工厂 */
    Json::StreamWriterBuilder writer_factory;
    /* 2.生产对象 */
    std::unique_ptr<Json::StreamWriter> json_writer(writer_factory.newStreamWriter());
    /* 3.序列化为JSON字符串 */
    std::stringstream json_stream;
    if (json_writer->write(json_value, &json_stream) != 0) {
        std::cout << "JSON serialization failed\n";
        return false;
    }
    json_string = json_stream.str();
    return true;
}

bool deserialize(const std::string &json_string, Json::Value &json_value) {
    /* 1.定义工厂 */
    Json::CharReaderBuilder reader_factory;
    /* 2.生产对象 */
    std::unique_ptr<Json::CharReader> json_reader(reader_factory.newCharReader());
    /* 3.JSON字符串反序列化 */
    std::string error_string;
    if (json_reader->parse(json_string.c_str(), 
                           json_string.c_str() + json_string.size(), 
                           &json_value, &error_string) == false) {
        std::cout << "JSON deserialization failed\n";
        return false;
    }
    return true;
}


int main() {
    Json::Value man;
    man["name"] = "Alice";
    man["age"] = 18;
    man["is_student"] = true;
    man["score"].append(88);
    man["score"].append(66.7);
    man["score"].append(99.6);

    std::string json_string;
    if (serialize(man, json_string) == false) return -1;
    else std::cout << "-----serialize result-----\n";
    std::cout << json_string << std::endl;

    Json::Value result;
    if (deserialize(json_string, result) == false) return -1;
    std::cout << "-----deserialize result-----\n";
    std::cout << result["name"] << std::endl;
    std::cout << result["age"] << std::endl;
    std::cout << result["score"][0] << ", " 
              << result["score"][1] << ", " 
              << result["score"][2] << std::endl;
              
    return 0;
}